<?php

require_once "./include.php";

/* Start Client and auth*/
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Drive List Files");
$client->setClientId($WEB_CLIENT_ID);
$client->setClientSecret($WEB_CLIENT_SECRET);
$client->setRedirectUri($WEB_CLIENT_REDIRECT_URIS[1]);
$client->setScopes($WEB_CLIENT_SCOPES);
$client->setUseObjects(true);
// $client->setDeveloperKey('insert_your_developer_key');
$oauth2 = new Google_Oauth2Service($client);

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
  return;
}

if (isset($_SESSION['token'])) {
 $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
  $client->revokeToken();
}

if ($client->getAccessToken()) {
  $user = $oauth2->userinfo->get();
  $_SESSION['token'] = $client->getAccessToken();

} else {
  $authUrl = $client->createAuthUrl();
}
  if(isset($user)) {
    $service = new Google_DriveService($client);
    $all_files = retrieveAllFiles($service); 
  }
?>
<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
<header><h1>Google UserInfo Sample App</h1></header>
<?php
  if(isset($user)) {
#    $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
#    var_dump($user);
    print "<div>Utente: $user->email</div>";
  } else {
    print "<div>Nessun utente: </div>";
  }
?>
<?php
  if(isset($all_files)) {
    var_dump($all_files);
  } else {
    print "<div>Nessun utente: </div>";
  }
?>
<?php
  if(isset($authUrl)) {
    print "<a class='login' href='$authUrl'>Connect Me!</a>";
  } else {
   print "<a class='logout' href='?logout'>Logout</a>";
  }
?>
</body></html>
